import random
from datetime import datetime

from asgiref.sync import async_to_sync
from bs4 import BeautifulSoup
from channels.layers import get_channel_layer
from django.contrib.auth import login, logout
from django.contrib.auth.hashers import make_password
from django.contrib.sessions.models import Session
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect, reverse
from django.views.generic import View
from pure_pagination import Paginator, PageNotAnInteger

from my_apps.live.models import LiveRoom
from my_apps.videos.models import Video, VideoHistory, VideoSub
from utils.delete_filed import video_sub_delete
from utils.send_email import send_register_email, random_str
from .forms import Reform, LoginForm, SendEmailForm, AddFavForm, ChangePicForm, ChangeInfoForm, \
    ChangePasswordForm, VideoUploadForm, VideoForm, RealNameAuthenticationForm, CheckEmailForm, ForgetPwdForm
from .models import UserProfile, EmailPro, UserFavorite, UserMessage, SecretQuestion, UserSecretAnswer


# Create your views here.


class UserView(View):
    """用户界面"""

    def get(self, request):
        fav_type = request.GET.get('fav_type')
        user = request.user
        data = {}
        data['fav_type'] = fav_type
        if not fav_type:
            data['fav_type'] = 'video'

        all_videos = []
        all_star = []
        # 收藏
        user_fav = UserFavorite.objects.filter(user=request.user)
        for fav in user_fav:
            if fav.fav_type == '1':
                video = Video.objects.get(id=fav.fav_id)
                all_videos.append(video)
            elif fav.fav_type == '2':
                star = UserProfile.objects.get(id=fav.fav_id)
                all_star.append(star)

        # 获取所有的观看记录
        all_video_history = VideoHistory.objects.filter(user=user).order_by('-modify_time')

        # 获取用户没有保存过的密保问题
        data['all_secret'] = SecretQuestion.objects.all().exclude(secret_question__user=request.user)
        data['user_secret'] = UserSecretAnswer.objects.filter(user_id=request.user.id)
        data['page_name'] = 'user'
        data['all_videos'] = all_videos[:5]
        data['all_star'] = all_star[:5]
        data['all_video_history'] = all_video_history[:3]
        return render(request, 'main_hub/user.html', data)


class UserMessageView(View):
    """用户消息界面"""

    def get(self, request):
        data = {}
        receive_message = UserMessage.objects.filter(to_user=request.user).values('user', 'add_time').order_by(
            'user').distinct()
        send_message = UserMessage.objects.filter(user=request.user).values('to_user', 'add_time').order_by(
            'to_user').distinct()

        all_user_q = receive_message.union(send_message).order_by('-add_time')
        all_user_dic = {}

        for u in all_user_q:
            user = UserProfile.objects.get(id=u['user'])
            if user != request.user:
                msg = UserMessage.objects.filter(user=user, to_user=request.user, has_read=False)
                if msg:
                    all_user_dic[user.username] = [user, False]
                if user.username not in [us for us in all_user_dic]:
                    all_user_dic[user.username] = [user, True]

        all_username = [us for us in all_user_dic]
        recipient_username = request.GET.get('recipient_username')
        if recipient_username == request.user.username:
            return redirect(reverse('user_message'))
        if not all_user_dic and not recipient_username:
            data['page_name'] = 'my_message'
            return render(request, 'main_hub/user_message.html', data)

        # 启用临时对话
        if recipient_username:
            try:
                recipient_user = UserProfile.objects.get(username=recipient_username)
                if recipient_user.username not in all_username:
                    data['not_recipient_user'] = recipient_user
                data['recipient_user'] = recipient_user
            except:
                return redirect(reverse('user_message'))
        else:
            recipient_user = UserProfile.objects.get(username=all_username[0])
            data['recipient_user'] = recipient_user

        sender = request.user
        qs_one = UserMessage.objects.filter(user=sender, to_user=recipient_user)  # A发送给B的信息
        qs_two = UserMessage.objects.filter(user=recipient_user, to_user=sender)  # B发送给A的信息
        qs_two.update(has_read=True)
        data['all_message'] = qs_one.union(qs_two).order_by('add_time')  # 取查到的信息内容的并集，相当于他两的聊天记录
        data['all_user_dic'] = all_user_dic
        data['group'] = request.user.id
        data['page_name'] = 'my_message'
        return render(request, 'main_hub/user_message.html', data)

    def post(self, request):
        user_id = request.POST.get('user_id')
        if not user_id:
            return JsonResponse({
                'status': 'fail',
                'msg': '参数错误'
            })
        recipient = UserProfile.objects.get(id=user_id)  # 消息接收者
        content = request.POST.get('content')  # 消息内容
        if not content:
            return JsonResponse({
                'status': 'fail',
                'msg': '请输入消息'
            })
        sender = request.user  # 发送者
        msg = UserMessage.objects.create(user=sender, to_user=recipient, message=content)  # 把消息存储到数据库
        qs_one = UserMessage.objects.filter(user=sender, to_user=recipient)  # A发送给B的信息
        channel_layer = get_channel_layer()
        # get_channel_layer()函数获得的是当前的websocket连接所对应的consumer类对象的channel_layer
        time = "{}:{} {}.{} ".format(str(msg.add_time.hour), str(msg.add_time.minute), str(msg.add_time.month),
                                     str(msg.add_time.day))
        payload = {
            'type': 'receive',  # 这个type是有限制的，比如现在用到的就是cusumer的receive函数
            'message': content,  # 消息内容
            'sender': request.user.username,  # 发送者
            'read_num': qs_one.filter(has_read=False).count(),
            'image': request.user.image.url,
            'receive': recipient.username,
            'send_nick_name': request.user.nick_name,
            'msg_id': msg.id,
            'time': time  # 创建时间
        }
        group_name = request.POST.get('group')  # 这里用的是接收者的用户名为组名，每个用户在进入聊天框后就会自动进入以自己用户名为组名的group
        # 在信息界面发送消息
        async_to_sync(channel_layer.group_send)(group_name, payload)
        # 在所有界面推送给接受用户
        async_to_sync(channel_layer.group_send)(recipient.username, payload)
        # 上一句是将channel_layer.group_send()从异步改为同步，正常的写法是channel_layer.group_send(group_name, payload)
        return JsonResponse({
            'status': 'success',
            'msg': '发送成功'
        })


class UserFavView(View):
    """用户收藏界面"""

    def get(self, request):
        fav_type = request.GET.get('fav_type')
        data = {}
        data['fav_type'] = fav_type
        if not fav_type:
            data['fav_type'] = 'video'
        all_videos = []
        all_star = []
        # 视频搜藏查询
        user_fav = UserFavorite.objects.filter(user=request.user)
        for fav in user_fav:
            if fav.fav_type == '1':
                video = Video.objects.get(id=fav.fav_id)
                all_videos.append(video)
            elif fav.fav_type == '2':
                star = UserProfile.objects.get(id=fav.fav_id)
                all_star.append(star)
        # 视频分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_videos, per_page=20, request=request)
        all_video = p.page(page)
        data['all_video'] = all_video
        # 所有关注用户分页
        try:
            page = request.GET.get('star_page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_star, per_page=20, request=request)
        all_star = p.page(page)
        data['all_star'] = all_star
        data['page_name'] = 'my_fav'
        return render(request, 'main_hub/user_fav.html', data)


class ChangePassword(View):
    """更改密码"""

    def post(self, request):
        # 重写form ___init__()
        form = ChangePasswordForm(request)
        if not form.is_valid():
            msg = BeautifulSoup(str(form.non_field_errors()), 'lxml').text
            return JsonResponse({
                'status': 'fail',
                'msg': msg
            })
        new_password = form.cleaned_data.get('new_password')
        # 更改密码
        request.user.password = make_password(new_password)
        request.user.save()
        return JsonResponse({
            'status': 'success',
            'msg': '更改成功'
        })


class UserVideoView(View):
    """用户视频页"""

    def get(self, request):
        data = {}
        video_list = Video.objects.filter(user=request.user)
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(video_list, per_page=40, request=request)
        all_video = p.page(page)

        data['all_video'] = all_video
        data['page_name'] = 'my_video'
        return render(request, 'main_hub/user_video.html', data)

    def post(self, request):
        """用户发布视频"""
        video_form = VideoForm(request.POST, request.FILES, instance=request.user)
        sub_form = VideoUploadForm(request.POST, request.FILES, instance=request.user)

        if video_form.is_valid() and sub_form.is_valid():
            name = video_form.cleaned_data.get('name')
            image = video_form.cleaned_data.get('image')
            info = video_form.cleaned_data.get('info')
            field = sub_form.cleaned_data.get('user_field')
            # 先保存视频, 再用sub保存文件   15为用户发布视频
            video = Video.objects.create(user=request.user, name=name, image=image, info=info,
                                         start_time=datetime.now(), video_type='15')
            video.video_sub.create(
                video=video,
                user_field=field
            )
            video.save()
            return redirect(reverse('user_video'))
        data = {}
        data['user_video'] = Video.objects.filter(user=request.user)
        data['video_error'] = '发布失败'
        return render(request, 'main_hub/user_video.html', data)


class UserVideoDeleteView(View):
    """用户删除个人视频"""

    def post(self, request):
        video_id = request.POST.get('video_id')
        if video_id:
            video = Video.objects.get(id=video_id)
            for fav in UserFavorite.objects.filter(fav_id=video_id):
                fav.delete()

            # 删除本地文件
            all_vs = VideoSub.objects.filter(video_id=video_id)
            for vs in all_vs:
                video_sub_delete(vs)
            video.delete()
            return JsonResponse({
                'status': 'success',
                'msg': '删除成功'
            })
        return JsonResponse({
            'status': 'fail',
            'msg': '参数错误'
        })


class UserMessageDeleteView(View):
    """用户消息删除"""

    def post(self, request):
        message_id = request.POST.get('message_id')
        if message_id:
            msg = UserMessage.objects.get(id=message_id)
            msg.delete()
            return JsonResponse({
                'status': 'success',
                'msg': '删除成功'
            })
        return JsonResponse({
            'status': 'fail',
            'msg': '参数错误'
        })


class UserHistory(View):
    """用户历史界面"""

    def get(self, request):
        data = {}
        all_video_history = VideoHistory.objects.filter(user=request.user).order_by('-modify_time')
        # 历史记录分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_video_history, per_page=20, request=request)
        all_video_history = p.page(page)

        data['all_video_history'] = all_video_history
        data['page_name'] = 'my_his'
        return render(request, 'main_hub/user_history.html', data)


class UserDeleteHistoryView(View):
    """用户删除历史记录"""

    def post(self, request):
        his_id = request.POST.get('his_id')
        if his_id:
            VideoHistory.objects.get(id=his_id).delete()
            return JsonResponse({
                'status': 'success',
                'msg': '删除成功'
            })
        return JsonResponse({
            'status': 'fail',
            'msg': '参数错误'
        })


class ChangePic(View):
    """修改用户头像"""

    def post(self, request):
        data = {}
        if not request.FILES:
            data['status'] = 'fail'
            data['msg'] = '请选择头像'
            return JsonResponse(data)

        image_form = ChangePicForm(request.POST, request.FILES, instance=request.user)
        if image_form.is_valid():
            image_form.save()
            data['status'] = 'success'
            data['msg'] = '修改成功'
            return JsonResponse(data)

        data['status'] = 'fail'
        data['msg'] = BeautifulSoup(str(image_form.non_field_errors()), 'lxml').text
        return JsonResponse(data)


class ChangeInfo(View):
    """修改个人信息"""

    def post(self, request):
        form = ChangeInfoForm(request.POST)
        data = {}
        data['status'] = 'fail'
        if not form.is_valid():
            data['msg'] = '请填写完整'
            return JsonResponse(data)

        nick_name = form.cleaned_data.get('nick_name')

        # 判定昵称是否重复
        user_list = UserProfile.objects.filter(nick_name=nick_name)
        for user in user_list:
            if user.nick_name == request.user.nick_name:
                data['msg'] = '昵称未更改！'
                return JsonResponse(data)
            if user.nick_name == nick_name:
                data['msg'] = '昵称已被其他用户注册，请更换昵称'
                return JsonResponse(data)

        birthday = form.cleaned_data.get('birthday')
        gender = form.cleaned_data.get('gender')
        address = form.cleaned_data.get('address')

        user = request.user
        user.nick_name = nick_name
        user.birthday = birthday
        user.gender = gender
        user.address = address
        user.save()
        data['status'] = 'success'
        data['msg'] = '修改成功'
        return JsonResponse(data)


class UserDetailView(View):
    """用户详情页面, 从视频页面点击"""

    def get(self, request):
        data = {}
        data["user"] = request.user
        user_name = request.GET.get('username')
        other_user = UserProfile.objects.get(username=user_name)
        data['other_user'] = other_user

        # 获取这个用户的所有视频发布
        video_list = Video.objects.filter(user=other_user)
        # 分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(video_list, per_page=20, request=request)
        all_video = p.page(page)
        data['all_video'] = all_video

        fav_user = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=other_user.id, fav_type='2'):
                fav_user = True
        data['fav_user'] = fav_user
        return render(request, 'main_hub/user_detail.html', data)


class ReView(View):
    """注册功能"""

    def post(self, request):
        re_form = Reform(request.POST)
        data = {}
        if not re_form.is_valid():
            data['status'] = 'fail'
            data['msg'] = BeautifulSoup(str(re_form.non_field_errors()), 'lxml').text
            return JsonResponse(data)

        # 验证通过 传入数据库
        user = UserProfile.objects.create_user(
            username=re_form.cleaned_data.get('username'),
            password=re_form.cleaned_data.get('password')
        )
        user.save()
        login(request, user)
        data['status'] = 'success'
        return JsonResponse(data)


class LoginView(View):
    """登录功能"""

    def post(self, request):
        form = LoginForm(request.POST)
        data = {}
        if not form.is_valid():
            data['msg'] = BeautifulSoup(str(form.non_field_errors()), 'lxml').text
            data['status'] = 'fail'
            return JsonResponse(data)

        login(request, form.cleaned_data.get('user'))

        # 保证只有一个用户登录
        session_key = request.session.session_key
        for session in Session.objects.filter(~Q(session_key=session_key), expire_date__gte=datetime.now()):
            data = session.get_decoded()
            if data.get('_auth_user_id', None) == str(request.user.id):
                session.delete()

        data['status'] = 'success'
        return JsonResponse(data)


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        request.session.clear()
        logout(request)
        return redirect(reverse('home'))


class SendEmailView(View):
    """邮箱注册模块"""

    def post(self, request):
        form = SendEmailForm(request.POST)
        data = {}
        if not form.is_valid():
            data['status'] = 'fail'
            data['msg'] = BeautifulSoup(str(form.non_field_errors()), 'lxml').text
            return JsonResponse(data)

        username = random_str()  # 随机生成用户名
        while UserProfile.objects.filter(username=username):
            username = random_str()

        email = form.cleaned_data.get('email')
        UserProfile.objects.create_user(
            username=username,
            password=form.cleaned_data.get('password'),
            email=email,
            is_active=False
        ).save()

        host = request.get_host()  # 当前运行的host
        send_register_email(email, host, 'register')
        data['status'] = 'success'
        data['msg'] = '已发送邮件，请到邮箱确认并验证!'
        return JsonResponse(data)


class ActiveUserView(View):
    """邮箱验证模块"""

    def get(self, request, active_code):
        all_codes = EmailPro.objects.filter(code=active_code)
        if all_codes:
            for recode in all_codes:
                email = recode.email
                user = UserProfile.objects.get(email=email)
                # 激活用户
                user.is_active = True
                user.save()
                login(request, user=user)
                # 验证成功之后删除验证码
                recode.delete()
            return render(request, 'main_hub/code.html', {
                'status': True
            })
        else:
            for recode in all_codes:
                # 删除数据库中的验证码
                recode.delete()
            return render(request, 'main_hub/code.html', {
                'status': False
            })


class BoundEmail(View):
    """绑定邮箱"""

    def post(self, request):
        form = CheckEmailForm(request.POST)
        if not form.is_valid():
            return JsonResponse({
                'status': 'fail',
                'msg': BeautifulSoup(str(form.non_field_errors()), 'lxml').text
            })

        email = form.cleaned_data.get('email')
        # 检查数据库是否存在邮箱
        if UserProfile.objects.filter(email=email):
            return JsonResponse({
                'status': 'fail',
                'msg': '已存在有邮箱，请更换邮箱'
            })
        # 生成code
        code = random_str(16)
        # 同过表单验证 给邮箱发送验证信息
        host = request.get_host()  # 当前运行的host
        try:
            send_register_email(email, host, 'bound', code, request.user.id)
        except:
            # 超时
            return JsonResponse({
                'status': 'fail',
                'msg': '链接超时'
            })
        return JsonResponse({
            'status': 'success',
            'msg': '已发送邮件，请到邮箱确认'
        })


class BoundEmailActive(View):
    """绑定邮箱验证"""

    def get(self, request, active_code):
        em = EmailPro.objects.filter(user_id=request.user.id, code=active_code, send_type='bound')
        if not em:
            return render(request, 'main_hub/code.html', {
                'status': False
            })
        # 保存邮箱
        user = UserProfile.objects.get(id=request.user.id)
        user.email = em.first().email
        user.save()

        # 删除这个用户的所有邮箱激活码
        em_list = EmailPro.objects.filter(user_id=request.user.id)
        if em_list:
            em_list.delete()

        return render(request, 'main_hub/code.html', {
            'status': True
        })


class FavView(View):
    """收藏功能"""

    def post(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({
                'status': 'fail',
                'msg': '用户未登录',
            })

        form = AddFavForm(request.POST)
        if form.is_valid():
            user = request.user
            fav_id = form.cleaned_data.get('fav_id')
            fav_type = form.cleaned_data.get('fav_type')
            # 查看是否被收藏
            us = UserFavorite.objects.filter(
                user=user,
                fav_id=fav_id,
                fav_type=fav_type
            )
            if us:
                us.delete()
                if fav_type == '1':
                    video = Video.objects.get(id=fav_id)
                    video.hav_num -= 1
                    if video.hav_num < 0:
                        video.hav_num = 0
                    num = video.hav_num
                    video.save()
                    return JsonResponse({
                        'status': 'success',
                        'msg': '收藏',
                        'num': num
                    })

                elif fav_type == '2':
                    user = UserProfile.objects.get(id=fav_id)
                    user.fans -= 1
                    if user.fans < 0:
                        user.fans = 0
                    num = user.fans
                    user.save()
                    return JsonResponse({
                        'status': 'success',
                        'msg': '关注',
                        'num': num
                    })

            else:
                UserFavorite.objects.create(
                    user=user,
                    fav_id=fav_id,
                    fav_type=fav_type
                ).save()
                if fav_type == '1':
                    video = Video.objects.get(id=fav_id)
                    video.hav_num += 1
                    if video.hav_num < 0:
                        video.hav_num = 0
                    num = video.hav_num
                    video.save()
                    return JsonResponse({
                        'status': 'success',
                        'msg': '取消收藏',
                        'num': num
                    })
                elif fav_type == '2':
                    user = UserProfile.objects.get(id=fav_id)
                    user.fans += 1
                    if user.fans < 0:
                        user.fans = 0
                    num = user.fans
                    user.save()
                    return JsonResponse({
                        'status': 'success',
                        'msg': '已关注',
                        'num': num
                    })
        else:
            return JsonResponse({
                'status': 'fail',
                'msg': '参数错误'
            })


class RealNameAuthentication(View):
    """实名认证"""

    def post(self, request):
        if request.user.is_certificate:
            # 如果已经实名
            return redirect(reverse('user'))

        form = RealNameAuthenticationForm(request.POST)
        if not form.is_valid():
            return JsonResponse({
                'status': 'fail',
                'msg': BeautifulSoup(str(form.non_field_errors()), 'lxml').text
            })

        real_name = form.cleaned_data.get('real_name')
        identity_card = form.cleaned_data.get('identify_card')

        # 查询数据库身份证是否已被认证
        if UserProfile.objects.filter(identity_card=identity_card):
            return JsonResponse({
                'status': 'fail',
                'msg': '信息已被认证'
            })

        # 通过表单验证 更改用户信息
        user = UserProfile.objects.get(id=request.user.id)
        user.real_name = real_name
        user.identity_card = identity_card
        user.is_certificate = True
        user.save()

        if LiveRoom.objects.filter(user=request.user):
            return JsonResponse({
                "status": "success"
            })

        # 分配直播间
        room_number = random.randint(10000, 99999)  # 随机分配房间号
        while LiveRoom.objects.filter(user=request.user):
            room_number = random.randint(10000, 99999)

        LiveRoom.objects.create(user=request.user, number=room_number, is_active=True).save()
        return JsonResponse({
            'status': 'success',
            'msg': '实名认证成功'
        })


class SaveSecretQuestion(View):
    """保存密保答案"""

    def post(self, request):
        question_id = request.POST.get('question')
        answer = request.POST.get('answer')
        if not question_id and not answer:
            return JsonResponse({
                'status': 'fail',
                'msg': '参数错误'
            })
        if UserSecretAnswer.objects.filter(user=request.user, question_id=question_id, answer=answer):
            return JsonResponse({
                'status': 'fail',
                'msg': '已保存过此问题'
            })
        UserSecretAnswer.objects.create(user=request.user, question_id=question_id, answer=answer)
        return JsonResponse({
            'status': 'success',
            'msg': '修改成功'
        })


class ForgetPwdView(View):
    """忘记密码"""

    def get(self, request):
        return render(request, 'main_hub/forget_pwd.html')

    def post(self, request):
        """更改密码"""
        user = request.POST.get('user')
        if not user:
            return JsonResponse({
                'status': 'fail',
                'msg': '参数错误'
            })
        form = ForgetPwdForm(request.POST)
        if not form.is_valid():
            return JsonResponse({
                'status': 'fail',
                'msg': BeautifulSoup(str(form.non_field_errors()), 'lxml').text
            })

        new_password = form.cleaned_data.get('new_password')
        # 获取用户
        try:
            user = UserProfile.objects.get(id=user)
        except:
            return JsonResponse({
                'status': 'fail',
                'msg': '参数错误'
            })
        # 删除这个用户的所有邮箱激活码
        em_list = EmailPro.objects.filter(user_id=user.id)
        if em_list:
            em_list.delete()

        # 保存密码
        user.password = make_password(new_password)
        user.save()
        return JsonResponse({
            'status': 'success',
            'msg': '密码修改成功'
        })


class UseSecretToGetPwd(View):
    """判断密保问题"""

    def post(self, request):
        data_id = request.GET.get('data_id')
        user = request.GET.get('user')
        if not data_id and not user:
            return JsonResponse({
                'status': 'fail',
                'msg': '参数错误'
            })

        # 处理数据id
        data_id = data_id.split(' ')
        for question_id in data_id:
            if question_id == '':
                data_id.remove(question_id)
            else:
                answer = request.POST.get(question_id)
                if not answer:
                    return JsonResponse({
                        'status': 'fail',
                        'msg': '请回答完整'
                    })
                if not UserSecretAnswer.objects.filter(user_id=user, question_id=question_id, answer=answer):
                    return JsonResponse({
                        'status': 'fail',
                        'msg': '回答存在错误，请仔细检查'
                    })
        return JsonResponse({
            'status': 'success'
        })


class CheckUser(View):
    """检擦是否存在用户"""

    def post(self, request):
        username = request.POST.get('username')
        if not username:
            return JsonResponse({
                'status': 'fail',
                'msg': '请输入用户名或邮箱'
            })
        user = None
        #  二进制 可以严格判定大小写  按照用户名和邮箱查找数据库
        user_username = UserProfile.objects.extra(where=["binary username=%s"], params=[username])
        user_email = UserProfile.objects.extra(where=["binary email=%s"], params=[username])
        if user_username:
            user = user_username
        elif user_email:
            user = user_email

        if not user:
            return JsonResponse({
                'status': 'fail',
                'msg': '用户不存在'
            })

        # 找到这个用户的所有密保问题
        user_answer = UserSecretAnswer.objects.filter(user=user.first()).values('user_id', 'question_id',
                                                                                'question__question').order_by('?')
        if user_answer.count() < 5:
            return JsonResponse({
                'status': 'fail',
                'msg': '设定问题过少，无法使用密保来找回密码'
            })

        random_user_answer = user_answer[:5]
        return JsonResponse({
            'status': 'success',
            'data': list(random_user_answer)
        })


class CheckEmailBound(View):
    """检查邮箱是否被绑定"""

    def post(self, request):
        username = request.POST.get('username')
        user = UserProfile.objects.extra(where=["binary username=%s"], params=[username])
        if not user:
            return JsonResponse({
                'status': 'fail',
                'msg': '用户不存在'
            })
        if not user.first().email:
            return JsonResponse({
                'status': 'fail',
                'msg': '用户未绑定邮箱'
            })
        return JsonResponse({
            'status': 'success'
        })


class RenewPwdSendEmail(View):
    """重置密码 邮件发送"""

    def post(self, request):
        username = request.POST.get('user')
        if not username:
            return JsonResponse({
                'status': 'fail',
                'msg': '参数错误'
            })
        # 查询此用户email
        try:
            user = UserProfile.objects.get(username=username)
        except:
            return JsonResponse({
                'status': 'fail',
                'msg': '参数错误'
            })
        email = user.email
        host = request.get_host()  # 当前运行的host
        try:
            # 发送邮件
            send_register_email(email, host, 'forget', user_id=user.id)
        except:
            return JsonResponse({
                'status': 'fail',
                'msg': '链接超时'
            })
        return JsonResponse({
            'status': 'success',
            'msg': '发送成功，请到邮箱查询！'
        })


class EmailRenewPwdView(View):
    """邮件重置密码页"""

    def get(self, request):
        code = request.GET.get('code')
        try:
            email = EmailPro.objects.get(send_type='forget', code=code)
        except:
            return redirect(reverse('home'))
        data = {}
        data['user'] = email.user
        return render(request, 'main_hub/email_renew_pwd.html', data)
